package com.hcw.framework.web.core;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.hcw.framework.service.BaseService;
import com.hcw.framework.service.ServiceException;
import com.hcw.framework.utils.OperateResultUtils;
import com.hcw.framework.web.bean.DefaultMessageCode;
import com.hcw.framework.web.bean.OperateResult;
import com.hcw.framework.web.utils.ValidatorUtils;

/**
 *
 * @ClassName： Controller 
 * @Description： 基础controller，封装了一些常用的方法
 * @author Huang,ChunWu
 * @param <T>
 * @date 2015年9月23日 下午12:22:44
 *
 */
public abstract class BaseController<E> {

	protected abstract BaseService<E> getBaseService();

	@RequestMapping("/add")
	@ResponseBody
	public OperateResult add(E entity, HttpServletRequest request) throws WebException {

		// 验证必填项
		String message = ValidatorUtils.validate(entity);

		try {
			getBaseService().add(entity);
		} catch (ServiceException e) {
			throw new WebException(DefaultMessageCode.WM_GLOBAL_METHOD_ERROR_PARAM, e.getLocalizedMessage());
		}

		return OperateResultUtils.generateSUCCESS(DefaultMessageCode.WM_GLOBAL_CREATE_SUCCESS, RequestContextUtils.getLocale(request));
	}

	/**
	 * Web异常处理,默认返回异常消息.
	 * 
	 * @param WebException
	 *            Web异常
	 * @return Message 异常消息
	 */
	@ExceptionHandler(WebException.class)
	@ResponseBody
	public OperateResult webExceptionHandler(WebException webException, HttpServletRequest request) {
		return OperateResultUtils.generateFAILURE(webException.getExceptionCode(), RequestContextUtils.getLocale(request));
	}

	/**
	 * Web异常处理,默认返回异常消息.
	 * 
	 * @param Web404Exception
	 *            Web404异常
	 * @return Message 异常消息
	 */
	@ExceptionHandler(Web403Exception.class)
	public String web404ExceptionHandler(Web403Exception web403Exception, HttpServletRequest request) {
		request.setAttribute("WEB_403_EXCEPTION", web403Exception);
		return "errors.403";
	}

	/**
	 * Web异常处理,默认返回异常消息.
	 * 
	 * @param Web404Exception
	 *            Web404异常
	 * @return Message 异常消息
	 */
	@ExceptionHandler(Web404Exception.class)
	public String web404ExceptionHandler(Web404Exception web404Exception, HttpServletRequest request) {
		request.setAttribute("WEB_404_EXCEPTION", web404Exception);
		return "errors.404";
	}

	/**
	 * Web异常处理,默认返回异常消息.
	 * 
	 * @param Web404Exception
	 *            Web404异常
	 * @return Message 异常消息
	 */
	@ExceptionHandler(Web500Exception.class)
	public String web500ExceptionHandler(Web500Exception web500Exception, HttpServletRequest request) {
		request.setAttribute("WEB_500_EXCEPTION", web500Exception);
		return "errors.500";
	}
}
